﻿using UnityEngine;
using System.Collections;

public class RollGaugeAnimation : MonoBehaviour {

	Animator [] animatorsL;
	Animator [] animatorsR;
	public float animSpeed=1.0f;
	public float timeSum;
	public bool bStartGauge;
	public bool bStop;
	public float animLength;
	public GameObject particleL;
	public GameObject particleR;
	Transform gaugeAnimTex;
	public float maxGaugeX;
	public float minGaugeX;
	public float gaugeX;
	public float gapGauge;

	void Awake()
	{
		animatorsL = gameObject.GetComponentsInChildren<Animator>();
		//animatorsR = transform.FindChild("GageR").gameObject.GetComponentsInChildren<Animator>();
		foreach(Animator animator in animatorsL)
		{
			glog.debug("animatorL "+animator.name);
			animator.speed = 0;

		}
		//foreach(Animator animator in animatorsR)
		//{
		//	glog.debug("animatorR "+animator.name);
		//	animator.speed = 0;
		//}
		animLength = 0.6f;//animator.GetCurrentAnimatorStateInfo(0).length;
	//	StartCoroutine("CoUpdateGauge");
		particleL.SetActive(false);
		//particleR.SetActive(false);

		gaugeAnimTex = transform.FindChild("GageAniTexture");
		//minGaugeX = 999;
		//maxGaugeX = -999;

		minGaugeX = -641.4918f;
		maxGaugeX = -257.9865f;
		gapGauge = maxGaugeX - minGaugeX;
	}

	void PlayAnimator(float speed)
	{
		foreach(Animator animator in animatorsL)
		{
			animator.speed = speed;
		}
		//foreach(Animator animator in animatorsR)
		//{
		//	animator.speed = speed;
		//}
	}

	public void StartGauge()
	{
		particleL.SetActive(true);
		//particleR.SetActive(true);
		StopCoroutine("CoUpdateGauge");
		timeSum=0;
		animSpeed=1;
		PlayAnimator(animSpeed);
		StartCoroutine("CoUpdateGauge");
	}

	public void Stop()
	{
		particleL.SetActive(false);
	//	particleR.SetActive(false);
		StopCoroutine("CoUpdateGauge");
		PlayAnimator(0);
	}

	IEnumerator CoUpdateGauge()
	{
		while(true)
		{
//			if(gaugeAnimTex.transform.localPosition.x > maxGaugeX)
//				maxGaugeX = gaugeAnimTex.transform.localPosition.x;
//			if(gaugeAnimTex.transform.localPosition.x < minGaugeX)
//				minGaugeX = gaugeAnimTex.transform.localPosition.x;

			gaugeX = gaugeAnimTex.transform.localPosition.x;
			gaugeX = gaugeX - minGaugeX;
			if(gaugeX<0)
				gaugeX=0;
			float ratio = gaugeX/gapGauge;
			timeSum = ratio * 6;
			/*
			timeSum += animSpeed * Time.deltaTime;
			if(timeSum>=animLength)
			{
				timeSum = animLength;
				animSpeed = -animSpeed;
				//PlayAnimator(animSpeed);
			}
			if(timeSum<=0)
			{
				timeSum=0;
				animSpeed = -animSpeed;
				//PlayAnimator(animSpeed);
			}*/


			yield return null;
		}
	}

	void ChangeSpeed(float s)
	{
		foreach(Animator animator in animatorsL)
		{
			animator.speed = s;
		}
		//foreach(Animator animator in animatorsR)
		//{
		//	animator.speed = s;
		//}
	}

	void Update()
	{
		if(bStartGauge)
		{
			bStartGauge = false;
			StartGauge();
		}
		if(bStop)
		{
			bStop=false;
			Stop ();
		}
	}

}
